//
//  WPIndivalInfoVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/2.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPIndivalInfoVC.h"
#import "HMDatePicker.h"
#import "NSDate+Extend.h"
#import "WPNickNameVC.h"
#import "WPSexPickerView.h"
#import "UIImage+AsyncDraw.h"
#import "LDImagePicker.h"
#import "WPBindingPhoneNumVC.h"
#import "WPPickerView.h"
#import "WPReplacePhoneNumVC.h"

#define MAX_IMAGE_COUNT 1

@interface WPIndivalInfoVC ()<HMDatePickerDelegate,UIActionSheetDelegate,LDImagePickerDelegate>

{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    
}
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nickName;
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumLabel;
@property(nonatomic,strong) WPUserAccount *userAccount;

@end

@implementation WPIndivalInfoVC

-(WPUserAccount *)userAccount
{
    if (_userAccount == nil)
    {
        _userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
    }
    return _userAccount;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [MobClick endLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    
    self.tableView.bounces = NO;
    self.navigationController.navigationBar.hidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [btn sizeToFit];
    [btn addTarget:self action:@selector(backBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacer.width = -8;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    
    self.iconView.layer.cornerRadius = 45*0.5;
    self.iconView.layer.masksToBounds = YES;
    
    self.birthdayLabel.text = [[NSDate date] stringFromDateFormat:@"yyyy-MM-dd"];
    
    [self loadUserInfo];

}


- (void)backBtnDidClick:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

-(void)loadUserInfo
{

    self.iconView.contentMode = UIViewContentModeScaleAspectFit;
    [self.iconView sd_setImageWithURL:[NSURL URLWithString:self.userAccount.user.image] placeholderImage:[UIImage imageNamed:@"touxiang3"]];
    
    self.nickName.text = self.userAccount.user.name;
    self.sexLabel.text = self.userAccount.user.sex;
    
   
    self.birthdayLabel.text = [[WPDateFormatterManager sharedManager] timeStrWithTimeStampStr:self.userAccount.user.birthday];
    
    if (self.userAccount.user.phone.length)
    {
        self.phoneNumLabel.text = self.userAccount.user.phone;
    }
    else
    {
        self.phoneNumLabel.text = @"未绑定";
    }
}


#pragma mark - tableView的代理方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0)
    {
        if (indexPath.item == 0)
        {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
            [sheet showInView:self.view];
        }
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.item == 0)
        {
            WPPickerView *pickerView = [[WPPickerView alloc] initWithData:@[@"男",@"女"] handleBlock:^(NSString *selectedData) {
                
                WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
                if ([userAccount.user.sex isEqualToString:selectedData])
                {
                    return ;
                }
                userAccount.user.sex = selectedData;
                NSString *url = @"user/updateUser.do";
                NSString *JSONStr = [userAccount.user yy_modelToJSONString];
                NSDictionary *dict = @{@"json":JSONStr};
                
                [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
                 {
                     NSDictionary *dict = (NSDictionary *)responseObject;
                     if ([dict[@"result"] isEqualToString:@"success"])
                     {
                         //            归档
                         [userAccount saveUserAccount];
                         [WPUserAccountViewModel sharedInstance].userAccount = nil;
                         self.sexLabel.text = selectedData;
                     }
                     else
                     {
                         //            考虑到账号过期的情况
                         if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                         {
                             //                账号过期
                             UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                             [alertView show];
                         }
                         else
                         {
                             [self showErrorInfoWithStatus:@"更新失败"];
                         }
                     }
                     
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     
                     [self showErrorInfoWithStatus:@"网络错误"];
                     
                 }];
            }];
            [pickerView show];
        }
        else if (indexPath.item == 1)
        {
            // 创建日期选择器
            HMDatePicker *pickerView = [HMDatePicker datePicker];
            // 设置代理
            pickerView.delegate = self;
            // 设置datePicker当前显示的时间
            pickerView.currentDate = [NSDate dateFromString:self.birthdayLabel.text format:@"yyyy-MM-dd"];
            // 显示
            [pickerView show];
        }
        else if (indexPath.item == 2)
        {
            if (!self.userAccount.user.phone.length)
            {
                WPBindingPhoneNumVC *vc = [WPBindingPhoneNumVC new];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        else if (indexPath.item == 3)
        {
            if(self.userAccount.user.phone.length)
            {
                WPReplacePhoneNumVC *vc = [WPReplacePhoneNumVC new];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else
            {
                [self showInfoStatus:@"请先绑定手机号"];
            }
        }
    }
}


- (void)datePickerDidValueChanged:(HMDatePicker *)datePicker
{
    WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[datePicker.datePicker.date timeIntervalSince1970]*1000];
    
    if ([userAccount.user.birthday isEqualToString:timeSp])
    {
        return ;
    }
    userAccount.user.birthday = timeSp;
    NSString *url = @"user/updateUser.do";
    NSString *JSONStr = [userAccount.user yy_modelToJSONString];
    NSDictionary *dict = @{@"json":JSONStr};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSDictionary *dict = (NSDictionary *)responseObject;
         if ([dict[@"result"] isEqualToString:@"success"])
         {
             //            归档
             [userAccount saveUserAccount];
             [WPUserAccountViewModel sharedInstance].userAccount = nil;
             
             
             self.birthdayLabel.text = [datePicker.datePicker.date stringFromDateFormat:@"yyyy-MM-dd"];
             // 刷新表格
             [self.tableView reloadData];
             
         }
         else
         {
             //            考虑到账号过期的情况
             if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
             {
                 //                账号过期
                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                 [alertView show];
             }
             else
             {
                 [self showErrorInfoWithStatus:@"更新失败"];
             }
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
         [self showErrorInfoWithStatus:@"网络错误"];
         
     }];
}

/**
 *  在执行segue跳转之前会调用来源控制器的该方法
 */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // 获得目标控制器
    UIViewController *destVc = segue.destinationViewController;
    if ([destVc isKindOfClass:[WPNickNameVC class]]) {
        WPNickNameVC *addVc = (WPNickNameVC *)destVc;
        addVc.nickNameLabel = self.nickName;
    }
}



#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    if (buttonIndex == 0)
    {
      [imagePicker showImagePickerWithType:ImagePickerCamera InViewController:self Scale:0.75];
        
    } else if (buttonIndex == 1)
    {
       [imagePicker showImagePickerWithType:ImagePickerPhoto InViewController:self Scale:0.75];   
    }
    
    
    
}

/****************************** 照片相关 *****************************/
- (void)imagePickerDidCancel:(LDImagePicker *)imagePicker{
    
}
- (void)imagePicker:(LDImagePicker *)imagePicker didFinished:(UIImage *)editedImage
{

    [editedImage WP_AsyncDrawImageWith:CGSizeMake(45, 45) bgColor:[UIColor  whiteColor] isCorner:YES finished:^(UIImage *image) {
        
        WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
        NSString *url = @"user/updateUser.do";
        NSString *JSONStr = [userAccount.user yy_modelToJSONString];
        NSDictionary *dict = @{@"json":JSONStr};
        
        NSString *totalPath = [documentPath stringByAppendingPathComponent:@"iconImage.jpg"];
        NSData *data = UIImageJPEGRepresentation(image, 1);
        
        [data writeToFile:totalPath atomically:NO];
        NSURL *imageURL = [NSURL fileURLWithPath:totalPath];

        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            [formData appendPartWithFileURL:imageURL name:@"file" error:nil];
            
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
        {
            WPLog(@"******%@",responseObject);
            
            if ([responseObject[@"result"] isEqualToString:@"success"])
            {
                NSDictionary *dict = (NSDictionary *)responseObject;
                NSDictionary *detail = dict[@"detail"];
                NSDictionary *user = detail[@"user"];
                //            保存头像的url
                userAccount.user.image = user[@"image"];
                //            归档
                [userAccount saveUserAccount];
                [WPUserAccountViewModel sharedInstance].userAccount = nil;
                
                NSString *imageURLStr = [WPUserAccountViewModel sharedInstance].userAccount.user.image;
                [self.iconView sd_setImageWithURL:[NSURL URLWithString:imageURLStr] placeholderImage:[UIImage imageNamed:@"touxiang3"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                    [self showSuccessInfoWithStatus:@"头像更新成功"];
                    
                }];
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    [alertView show];
                }
                else
                {
                    [self showErrorInfoWithStatus:@"更新失败"];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            WPLog(@"%@",error);
        }];
        
    }];
}


/**
 *  跳转前时触发，如果返回NO,阻止跳转
 *  @param identifier identifier代表的是segue的identifier，而不是storyboard中控制器的identifier。 这里的identifier其实与prepareForSegue：sender 方法中的[segue identifier]其实是同一个id
 *  @param sender     sender代表触发跳转事件的控件，这里代表登陆的Button
 *
 *  @return YES 跳转，NO 阻止storyboard跳转
 */
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender
{
    
    //阻止跳转
    if([identifier isEqualToString:@"replacePhoneNum"] && self.userAccount.user.phone.length == 0){
        
        if (!self.userAccount.user.phone.length)
        {
            [self showInfoStatus:@"请先绑定手机号"];
        }
        return NO;
    }
    return YES;
}

-(void)dealloc
{
//    NSLog(@"个人信息控制器死了");
}

@end
